package com.jay.lang.clazz.jsr199;

import java.util.Arrays;
import java.util.List;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class AdvancedCompilationTest {
	public static void main(String[] args) throws Exception {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				diagnosticsCollector, null, null);
		JavaFileObject javaObjectFromString = getJavaFileContentsAsString();
		Iterable<? extends JavaFileObject> fileObjects = Arrays
				.asList(javaObjectFromString);
		CompilationTask task = compiler.getTask(null, fileManager,
				diagnosticsCollector, null, null, fileObjects);
		Boolean result = task.call();
		List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector
				.getDiagnostics();
		for (Diagnostic<? extends JavaFileObject> d : diagnostics) {
			// Print all the information here.
		}
		if (result == true) {
			System.out.println("Compilation has succeeded");
		} else {
			System.out.println("Compilation fails.");
		}
	}

	static SimpleJavaFileObject getJavaFileContentsAsString() {
		StringBuilder javaFileContents = new StringBuilder(""
				+ "class TestClass{" + "	public void testMethod(){"
				+ "		System.out.println(" + "\"test\"" + ");" + "}" + "}");
		JavaObjectFromString javaFileObject = null;
		try {
			javaFileObject = new JavaObjectFromString("TestClass",
					javaFileContents.toString());
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return javaFileObject;
	}

}
